package com.sne.airways.system.filters;

import com.sne.airways.basecore.constants.StatusCode;
import com.sne.airways.basecore.exceptions.SessionException;
import com.sne.airways.basecore.utils.ErrorMessage;
import com.sne.airways.basecore.utils.JSONUtils;
import com.sne.airways.system.utils.AppUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: 卞京帅 {bjslogin#gmail.com}
 * Date: 12-11-11
 * Time: 上午11:23
 * To change this template use File | Settings | File Templates.
 */
public class PowerFilter implements Filter {
    private Logger logger = Logger.getLogger(getClass());
    protected static final String sessionErrorPage = "/jsp/error/sessionError.jsp";
    protected static final String noPermissionPage = "/jsp/error/noPermission.jsp";
    protected static final String[] noFilterPages = {"/login","/logout","/main.jsp","/"};

    public void init(FilterConfig filterConfig) throws ServletException {
        // do nothing
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String url = StringUtils.substringAfter(request.getRequestURI(), request.getContextPath());
        logger.info("【" + request.getRemoteHost() + "[at]" + new Date() + "】" + url);

        url = StringUtils.substringBefore(url, "?");
        if (url.indexOf(".") > 0) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        for (String c : noFilterPages) {
            if (StringUtils.equals(c, url)) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        // todo 判断session
        try {
            AppUtils.getCurrentUser();
        } catch (SessionException e) {
            e.printStackTrace();
            ErrorMessage errorMessage = new ErrorMessage();
            errorMessage.setStatusCode(StatusCode.用户登录信息失效);
            errorMessage.setErrorMessage(e.getMessage());
            JSONUtils.renderJson(errorMessage);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {

    }

}
